import json
from typing import List

from .data_define import Record


class FileReader:
    def read_data(self) -> List[Record]:
        """
        读取文件的数据，转换为Record对象，封装到list内
        """
        pass


class TextFileReader(FileReader):
    def __init__(self, file_path):
        self.file_path = file_path

    def read_data(self) -> List[Record]:
        """
        读取文件的数据，转换为Record对象，封装到list内
        """
        f = None
        data = []
        try:
            f = open(self.file_path, "r", encoding="utf-8")
            data = f.readlines()
        except FileNotFoundError:
            print("文件不存在")
            return []
        finally:
            if f:
                f.close()
        if len(data) == 0:
            return []
        record_list = []
        for line in data:
            line = line.strip()
            line_data = line.split(",")
            record = Record(line_data[0], line_data[1], int(line_data[2]), line_data[3])
            record_list.append(record)
            # print(f"日期：{record.date}\t订单号：{record.order_id}\t金额：{int(record.money)}\t省：{record.province}")
        return record_list


class JsonFileReader(FileReader):
    def __init__(self, file_path):
        self.file_path = file_path

    def read_data(self) -> List[Record]:
        f = None
        data = []
        try:
            f = open(self.file_path, "r", encoding="utf-8")
            data = f.readlines()
        except Exception as e:
            print(e)
            return []
        finally:
            if f:
                f.close()
        if len(data) == 0:
            return []
        record_list = []
        for line in data:
            line = line.strip()
            data_dict = json.loads(line)
            record = Record(data_dict["date"], data_dict["order_id"], int(data_dict["money"]), data_dict["province"])
            record_list.append(record)
            # print(f"日期：{record.date}\t订单号：{record.order_id}\t金额：{int(record.money)}\t省：{record.province}")
            # print(record)
        return record_list
